package cn.diancan.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FtlUtils {
    
	public static String SYSTEM_ENCODING ="UTF-8"; 
	private Configuration cfg;
	public static String freeBasePath="D:/ProgramFiles/workspace/fangjxc/WebContent"; 
	
	public static  String projectPath = "D:/ProgramFiles/workspace/skyjson/";
	public static String savePath = "src/com/media/dao/"; 
    
    public void init(boolean useConfig) throws Exception {
    	// 初始化FreeMarker配置
    	// 创建一个Configuration实例
	if(!useConfig){
	    String tempSrc = Class.forName(FtlUtils.class.getName()).getResource("/").getPath();
	    freeBasePath = tempSrc.substring(0, tempSrc.length()-"WEB-INF/classes/".length());
	}
	
    	cfg = new Configuration();
    	// 设置FreeMarker的模版文件位置
    	cfg.setDirectoryForTemplateLoading(new File(freeBasePath));
    } 
    
    
    
    public String buildTemplate(Map<String,Object> root,  String templateName)throws Exception {
    	Template template = cfg.getTemplate(templateName); 
	try { 
		Writer out = new StringWriter();   
		template.process(root, out); 
		//System.out.println(out); 
		return out.toString();
	} catch (Exception e) {
		e.printStackTrace();
	} 
	return null;
    }
    
    
    
    public void buildTemplate(Map<String,Object> root, String fileName,String templateName)throws Exception { 
    	buildTemplate(root, projectPath, savePath, fileName, templateName);
    }
    
    public void buildTemplate(Map<String,Object> root, String projectPath, String savePath,String fileName,String templateName)throws Exception {
    	Template template = cfg.getTemplate(templateName); 
    
	String realFileName = projectPath + savePath + fileName;

	String realSavePath = projectPath + "/" + savePath;

	File newsDir = new File(realSavePath);
	if (!newsDir.exists()) {
		newsDir.mkdirs();
	} 
	try { 
		Writer out = new OutputStreamWriter(new FileOutputStream( realFileName), SYSTEM_ENCODING); 
		template.process(root, out); 
		//System.out.println(out); 
	} catch (Exception e) {
		e.printStackTrace();
	} 
    }
    
    
    

}
